
(function($){
    $.fn.parseForm=function(){
        var serializeObj={};
        var array=this.serializeArray();
        var str=this.serialize();
        $(array).each(function(){
            if(serializeObj[this.name]){
                if($.isArray(serializeObj[this.name])){
                    serializeObj[this.name].push(this.value);
                }else{
                    serializeObj[this.name]=[serializeObj[this.name],this.value];
                }
            }else{
                serializeObj[this.name]=this.value;
            }
        });
        return serializeObj;
    };
})(jQuery);

var loginAjax = function(opt, url, method){
    $.ajax({
        type: method,
        url: "/api"+url,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        },
        data: opt,// 要提交的表单
        success: function (msg) {
            console.info(msg)
            $.cookie('myToken', msg.data.token, { expires: 1 });
            window.location.href="/main.html";
        },
        error: function (error) {
            layer.alert('用户名或密码错误', {
                icon: 2,
                title: "登陆提示"
            })
        }
    })
}



var myAjaxSync = function(opt, url, method){
    var header = {};
    if($.cookie("myToken")){
        header["Authorization"] = "Bearer "+$.cookie("myToken")
    }
    $.ajax({
        type: method,
        url: "/api"+url,
        data: opt,// 要提交的表单
        headers: header,
        success: function (msg) {
            console.info(msg)
            return msg;
        },
        error: function (error) {
            if(error.status=='401'){
                layer.alert('请重新登陆', {
                    icon: 2,
                    title: "请求提示"
                })
                window.location.href="/login.html";
            }else {
                layer.alert('请求错误', {
                    icon: 2,
                    title: "请求提示"
                })
            }

        }
    })
}

var myAjax = function(opt, url, method){
    var dataInfo;
    var header = {};
    if($.cookie("myToken")){
        header["Authorization"] = "Bearer "+$.cookie("myToken")
    }
    $.ajax({
        type: method,
        url: "/api"+url,
        data: opt,// 要提交的表单
        headers: header,
        async: false, // 同步
        success: function (msg) {
            dataInfo = msg;
        },
        error: function (error) {
            dataInfo = {"code":"5000"};
            if(error.status=='401'){
                promptDail("请重新登陆！");
                window.location.href="/login.html";
            }else {
                promptDail("请求错误！");
            }
        }
    })
    return dataInfo;
};

var myAjaxJSON = function(opt, url, method){
    var dataInfo;
    var header = {};
    if($.cookie("myToken")){
        header["Authorization"] = "Bearer "+$.cookie("myToken")
    }
    $.ajax({
        type: method,
        url: "/api"+url,
        data: JSON.stringify(opt),// 要提交的表单
        headers: header,
        contentType: "application/json",
        dataType:"json",
        async: false, // 同步
        success: function (msg) {
            dataInfo = msg;
        },
        error: function (error) {
            dataInfo = {"code":"500"};
            if(error.status=='401'){
                promptDail("请重新登陆！");
                window.location.href="/login.html";
            }else {
                promptDail("请求错误！");
            }

        }
    })
    return dataInfo;
};

var postBody = function(opt, url){
    var tokens = "Bearer "+$.cookie("myToken");
    $.ajax({
        type: "POST",
        url: url,
        headers:{
            "Content-Type": "application/json;charset=utf-8",
            "Authorization": tokens,
        },
        data: opt,// 要提交的表单
        success: function (msg) {
            return msg;
        },
        error: function (error) {
            if(error.status=='401'){
                layer.alert('请重新登陆', {
                    icon: 2,
                    title: "请求提示"
                })
                window.location.href="/login.html";
            }else {
                layer.alert('请求错误', {
                    icon: 2,
                    title: "请求提示"
                })
            }

        }
    })
}

var successAlert = function(){
    layer.alert('请求成功', {
        icon: 1,
        title: "请求提示"
    })
}

var errorAlert = function(){
    layer.alert('请求失败', {
        icon: 2,
        title: "请求提示"
    })
}

var btnPurid = "";
$(function () {
    //显示按钮
    showPurWiewBtn();

    //时间选择器
    if( $(".form_date").length>0){
        $(".form_date").datetimepicker({
            language:  'zh-CN',
            weekStart: 1,
            todayBtn:  1,
            autoclose: 1,
            todayHighlight: 1,
            startView: 2,
            minView: 2,
            forceParse: 0
        });
    }

})

$(window).scroll(function () {
    pageInitModule.setScrollToTop();
});

var pageInitModule = (function (mod) {
    mod.setScrollToTop = function () {
        var top = $(window).scrollTop();
        if (top < 60) {
            $('#goTop').hide();
        } else {
            $('#goTop').show();
        }
    }

    return mod;
})(window.pageInitModule || {});

function getQueryString(name) {
    /**获得页面参数 "?btnPurid="+showHtml.id*/
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

function GetRequest() {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        var strs = str.split("&");
        for(var i = 0; i < strs.length; i ++) {
            theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}

//失去焦点判断是否为空
function onBlurValue(obj) {
    var info = $(obj).val();
    if(info!=null&&info!=""){
        $(obj).next().hide();
    }else {
        $(obj).next().show();
    }

}

function checkValue(infoId) {
    var b = true;
    var info = $("#"+infoId).val();
    if(info!=null&&info!=""){
        $("#"+infoId).next().hide();
    }else {
        $("#"+infoId).next().show();
        b = false;
    }

    return b;
}

function promptDail(infos, url) {
    dialog({
        title: '提示信息',
        width: "300px",
        content: infos,
        okValue: '确定',
        ok: function () {
            if(url!=null&&url!=""){
                window.location.href=url;
            }
        }
    }).showModal();
}

function errorDail(infos,url) {
    dialog({
        title: '错误信息',
        width: "300px",
        content: infos,
        okValue: '确定',
        ok: function () {
            if(url!=null&&url!=""){
                window.location.href=url;
            }
        }
    }).showModal();
}


function okDail(infos,url) {
    dialog({
        title: '成功',
        width: "300px",
        content: infos,
        okValue: '确定',
        ok: function () {
            if(url!=null&&url!=""){
                window.location.href=url;
            }
        }
    }).showModal();
}

function showPurWiewBtn() {
    btnPurid = getQueryString("btnPurid");
    var localUrl = "/api/roleAuth/getResBtn?access_token="+$.cookie("myToken");
    if(btnPurid!=null&&btnPurid!=""){
        $.get(localUrl, {"parentId":btnPurid}, function (infos) {
            var data = infos.data;
            if(data!=null&&data.length>0){
                for(var i=0;i<data.length;i++){
                    $("#"+data[i].url).show();
                }
            }
        },"json")
    }
}

function saveCommon(url, data, method) {
    var b = false;
    var result = myAjaxJSON(data, url, method);
    if(result.code=="200"){
        b = true;
        promptDail("保存成功！");
    }else if(result.code!="5000") {
        promptDail("保存失败！");
    }

    return b;
}

function commonInitTable(url, initTable, queryData) {
    //先销毁表格
    $('#'+initTable).bootstrapTable('destroy');
    var localUrl = "/api"+url+"?access_token="+$.cookie("myToken");

    //初始化表格,动态从服务器加载数据
    $("#"+initTable).bootstrapTable({
        method: "get",  //使用get请求到服务器获取数据
        url: localUrl, //获取数据的Servlet地址
        sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
        queryParamsType:'',
        cache: false,
        striped: true,
        contentType: "application/json",
        queryParams: function queryParams(params) {   //设置查询参数
            var param = {
                pageNumber: params.pageNumber,
                pageSize: params.pageSize,
            };
            param = $.extend({}, param, queryData)
            return param;
        }, responseHandler: function (res) {
            console.info(res);
            return res.data;
        }
    });
}

function removeCommon( url, options) {
    dialog({
        title: "删除",
        content: "确认删除信息",
        width: '100px',
        okValue: "确定删除",
        ok : function () {
            var result =  myAjax(options, url, "DELETE");
            if(result.code=="200"){
                promptDail("删除成功！");
            }else if(result.code!="5000") {
                promptDail("删除失败！");
            }

        },
        onremove: function () {
            initTable();
        },
        cancelValue: '取消',
        cancel: function () {}
    }).showModal();

}
